﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UtilZ.Dotnet.Ex.Base
{
    /// <summary>
    /// 环境扩展类
    /// </summary>
    public partial class EnvironmentEx
    {
        /// <summary>
        /// 获取系统已安装的.NET版本
        /// </summary>
        /// <returns></returns>
        public static Version GetFrameworkVersion()
        {
            string registerKey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
            var defaultVersion = new Version(0, 0);
            try
            {
                using (var sub = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(registerKey))
                {
                    if (!(sub?.GetValue("Release") is int key))
                        return defaultVersion;

                    //判断
                    if (key >= 528040)
                        return new Version(4, 8);
                    if (key >= 461808)
                        return new Version(4, 7, 2);
                    if (key >= 461308)
                        return new Version(4, 7, 1);
                    if (key >= 460798)
                        return new Version(4, 7);
                    if (key >= 394802)
                        return new Version(4, 6, 2);
                    if (key >= 394254)
                        return new Version(4, 6, 1);
                    if (key >= 393295)
                        return new Version(4, 6);
                    if (key >= 379893)
                        return new Version(4, 5, 2);
                    if (key >= 378675)
                        return new Version(4, 5, 1);
                    if (key >= 378389)
                        return new Version(4, 5);
                }
            }
            catch (Exception)
            {
                // ignored
            }
            //小于4.5，一般不存在这个环境
            return new Version(0, 0);
        }
    }
}
